package org.richin.file.filter;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.richin.file.util.FileUtils;

/**
 * Filters files by their extension
 * @created Sep 20, 2008 9:19:38 AM
 * @author Connor Garvey
 * @version 0.0.1
 * @since 0.0.1
 */
public class ExtensionFileFilter implements FileFilter {
  private Set<String> extensions;
  private static final String EXTENSION_SEPARATOR = ".";

  /**
   * Filters files by extension
   * @param extensions The extensions to accept
   */
  public ExtensionFileFilter(String... extensions) {
    this.extensions = new HashSet<String>();
    this.extensions.addAll(Arrays.asList(extensions));
  }
  public boolean accept(File pathname) {
    if (!pathname.isFile()) {
      return false;
    }
    String extension = this.getExtension(pathname.getPath());
    return extensions.contains(extension);
  }

  private String getExtension(String filePath) {
    String fileName = FileUtils.getFileName(filePath);
    int extensionSeparatorIndex = fileName.lastIndexOf(EXTENSION_SEPARATOR);
    if (extensionSeparatorIndex != -1) {
      return fileName.substring(extensionSeparatorIndex + 1);
    }
    return "";
  }

}
